package cn.xuchunh.tiq.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;

import cn.xuchunh.tiq.R;
import cn.xuchunh.tiq.net.SimpleHttpRequest;
import cn.xuchunh.tiq.storage.sp.SharedPreferenceManager;

/**
 * Created by XuChunH on 2016/4/18.
 */
public class QueryFragment extends Fragment implements View.OnClickListener {

    public static final String URL = "http://m.join.qq.com/query/result";
    public static final String TAG = QueryFragment.class.getSimpleName();

    private EditText etIdCard;
    private EditText etPhone;

    private ProgressDialog progressDialog;

    private RequestQueue requestQueue;
    private SharedPreferenceManager sharedPreferenceManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        requestQueue.start();
        sharedPreferenceManager = SharedPreferenceManager.getInstance(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_query, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        etIdCard = (EditText) view.findViewById(R.id.idcard);
        etPhone = (EditText) view.findViewById(R.id.phone);
        view.findViewById(R.id.query).setOnClickListener(this);
        etIdCard.setText(sharedPreferenceManager.getIDCard());
        etPhone.setText(sharedPreferenceManager.getPhone());
    }

    @Override
    public void onDestroy() {
        requestQueue.stop();
        requestQueue = null;
        sharedPreferenceManager = null;
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        String idCard = etIdCard.getEditableText().toString();
        String phone = etPhone.getEditableText().toString();
        if (TextUtils.isEmpty(idCard) || idCard.length() != 4) {
            Toast.makeText(getActivity(), "省份证错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getActivity(), "手机号错误", Toast.LENGTH_SHORT).show();
            return;
        }
        sharedPreferenceManager.setIDCard(idCard);
        sharedPreferenceManager.setPhone(phone);
        hideInput();
        showProgress();
        query(idCard, phone);
    }

    private void showProgress() {
        hideProgress();
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在查询，请稍后");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    private void hideProgress() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    private void hideInput() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
    }

    private void query(String idCard, String phone) {
        HashMap<String, String> params = new HashMap<>();
        params.put("type", "query_result");
        params.put("idcard", idCard);
        params.put("phone", phone);
        SimpleHttpRequest simpleHttpRequest = new SimpleHttpRequest(Request.Method.POST, URL, params, responseListener, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                hideProgress();
                Toast.makeText(getActivity(), "查询失败", Toast.LENGTH_SHORT).show();
                Log.d(TAG, error.getMessage());
            }
        });
        requestQueue.add(simpleHttpRequest);
    }

    private Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            hideProgress();
            MainActivity mainActivity = (MainActivity) getActivity();
            mainActivity.showResult(response);
        }
    };
}
